package com.king.zk.app;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 模拟服务器的上线和下线
 */
public class Server {

    private String connectString ="hadoop102:2181,hadoop103:2181,hadoop104:2181";
    private int sessionTimeout = 10000;
    private ZooKeeper  zookeeper ;
    private String serverZnode ="/servers" ;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        Server server = new Server() ;
        //1. 初始化zookeeper的连接
        server.initConenct();
        //2. 在zookeeper中的某个Znode中创建临时节点
        server.regist(args[0]);
        //3. 保持连接状态
        TimeUnit.MILLISECONDS.sleep(Long.MAX_VALUE);
    }

    private void regist(String data) throws KeeperException, InterruptedException {
        Stat stat = zookeeper.exists(serverZnode, false);
        if(stat == null ){
            zookeeper.create(serverZnode,"servers".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        }

        //在/servers中创建当前服务器对应的znode
        String s = zookeeper.create(serverZnode + "/server", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        System.out.println(s + " Is On Line！！！！！");
    }


    private void initConenct() throws IOException {
        zookeeper  = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

            }
        });
    }
}
